package com.zwj.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwj.common.utils.PageUtils;
import com.zwj.common.utils.Query;
import com.zwj.product.dao.CategoryDao;
import com.zwj.product.entity.CategoryEntity;
import com.zwj.product.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //递归查询出所有商品分类
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        List<CategoryEntity> treeList = entityList.stream()
                .filter(item -> item.getParentCid() == 0) //筛选出所有父类
                .map(menu -> {
                    menu.setChildren(getCategoryChildren(entityList, menu.getCatId()));
                    return menu;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        return treeList;
    }

    @Override
    public void removeMenuByIds(List<Long> catIds) {
        //TODO 逻辑删除前的校验
        if (CollectionUtils.isEmpty(catIds)) {
            return;
        }
        baseMapper.deleteBatchIds(catIds);
    }

    /**
     * 迭代获取子商品分类
     *
     * @param entityList
     * @param catId
     * @return
     */
    private List<CategoryEntity> getCategoryChildren(List<CategoryEntity> entityList, Long catId) {
        if (CollectionUtils.isEmpty(entityList)) {
            return null;
        }
        List<CategoryEntity> treeList = entityList.stream()
                .filter(menu -> catId.equals(menu.getParentCid())) //筛选出父id = catId的数据
                .map(menu -> {
                    menu.setChildren(getCategoryChildren(entityList, menu.getCatId()));
                    return menu;
                })  //递归查询 子数据
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

        return treeList;
    }
}